package org.jeecg.modules.flowable.converter;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.TextNode;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.constants.BpmnXMLConstants;
import org.flowable.bpmn.model.Activity;
import org.flowable.bpmn.model.ExtensionAttribute;
import org.flowable.bpmn.model.ExtensionElement;
import org.flowable.bpmn.model.FlowNode;
import org.flowable.editor.language.json.converter.BpmnJsonConverter;
import org.flowable.editor.language.json.converter.util.JsonConverterUtil;

import java.util.Collections;
import java.util.List;
import java.util.Map;

public class CustomBpmnJsonConverter extends BpmnJsonConverter {
    static {
        CustomUserTaskJsonConverter.customFillTypes(convertersToBpmnMap, convertersToJsonMap);
        CustomCallActivityJsonConverter.customFillTypes(convertersToBpmnMap, convertersToJsonMap);
        CustomSubProcessJsonConverter.customFillTypes(convertersToBpmnMap, convertersToJsonMap);
        CustomStartEventJsonConverter.customFillTypes(convertersToBpmnMap, convertersToJsonMap);
    }

    public static void addExtensionElement(JsonNode objectNode, FlowNode node, String name) {
        JsonNode expansionNode = JsonConverterUtil.getProperty(name, objectNode);
        if (null == expansionNode) {
            return;
        }
        if (!(expansionNode instanceof TextNode)) {
            return;
        }
        if (StringUtils.isBlank(expansionNode.asText())) {
            return;
        }
        ExtensionElement extensionElement = new ExtensionElement();
        extensionElement.setName(name);
        extensionElement.setNamespacePrefix(BpmnXMLConstants.FLOWABLE_EXTENSIONS_PREFIX);
        extensionElement.setNamespace(BpmnXMLConstants.FLOWABLE_EXTENSIONS_NAMESPACE);
        extensionElement.setElementText(expansionNode.asText());
        node.addExtensionElement(extensionElement);
    }

    public static void addExtensionAttributes(JsonNode objectNode, Activity activity, String name) {
        JsonNode expansionNode = JsonConverterUtil.getProperty(name, objectNode);
        if (null == expansionNode) {
            return;
        }
        if (!(expansionNode instanceof TextNode)) {
            return;
        }
        if (StringUtils.isBlank(expansionNode.asText())) {
            return;
        }
        Map<String, List<ExtensionAttribute>> attributes = activity.getAttributes();
        ExtensionAttribute attribute = new ExtensionAttribute();
        attribute.setName(name);
        attribute.setNamespacePrefix(BpmnXMLConstants.FLOWABLE_EXTENSIONS_PREFIX);
        attribute.setNamespace(BpmnXMLConstants.FLOWABLE_EXTENSIONS_NAMESPACE);
        attribute.setValue(expansionNode.asText());
        attributes.put(name, Collections.singletonList(attribute));
        activity.setAttributes(attributes);
    }
}